package com.bsh.shiro;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.web.filter.authc.AnonymousFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
/**
 * 
 * @author gsh
 *
 */
public class ApiFilter extends AnonymousFilter {
	private static Logger log = LoggerFactory.getLogger(ApiFilter.class);
	@Value("${fix_time}")
	String fixTime;
	
    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) {
    	try {
    		response.setContentType("text/json; charset=utf-8");
    		SimpleDateFormat sdf=new SimpleDateFormat("HH:mm");
    		Date tmBegin=sdf.parse(fixTime.split("-")[0]);
    		Date tmEnd=sdf.parse(fixTime.split("-")[1]);
    		
    		Date dt=new Date();
    		Date now=sdf.parse(String.format("%s:%s",dt.getHours(),dt.getMinutes()));
    		if(now.getTime()>=tmBegin.getTime() && now.getTime()<tmEnd.getTime()){
			   response.getWriter().print("{\"code\":\"401\",\"message\":\"凌晨00:01~00:15系统结算,暂停服务\"}");
			   return false;
    		}
		} catch (IOException e) {			
			e.printStackTrace();
		} catch (ParseException e) {
			log.error(String.format("维护时间配置错误：%s。\n%s",fixTime,e.getMessage()));
			e.printStackTrace();
		}    	
        return true;
    }
}
